﻿@page "/Account/Manage/DeletePersonalData"

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Identity
@using MyApp.Data
@using MyApp.Identity

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject UserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<DeletePersonalData> Logger

<PageTitle>Delete Personal Data</PageTitle>

<Heading3>Delete Personal Data</Heading3>

<div class="max-w-xl">
    <Alert Type="AlertType.Error" class="mb-3">
        Deleting this data permanently removes your account, and cannot be recovered.
    </Alert>

    <div class="mt-3 shadow overflow-hidden sm:rounded-md">
        <div class="px-4 bg-white dark:bg-black sm:p-6">
            <StatusMessage Message="@_message" />

            <EditForm class="mt-3" id="delete-user" Model="Input" FormName="delete-user" OnValidSubmit="OnValidSubmitAsync" method="post">
                <DataAnnotationsValidator />
                <ValidationSummary class="mt-2 text-danger text-sm" />

                <div class="flex flex-col gap-4">
                    @if (_requirePassword)
                    {
                        <div>
                            <label for="password" class="@TextInput.LabelClasses">Password</label>
                            <div class="mt-1 relative rounded-md shadow-sm">
                                <InputText id="password" type="password" @bind-Value="Input.Password" class="@TextInput.InputClasses" autocomplete="current-password" aria-required="true" placeholder="Please enter your password." />
                            </div>
                            <ValidationMessage For="() => Input.Password" class="mt-2 text-danger text-sm" />
                        </div>
                    }
                    <PrimaryButton Style="ButtonStyle.Red" type="submit">Delete data and close my account</PrimaryButton>
                </div>
            </EditForm>
        </div>
    </div>
</div>


@code {
    private string? _message;
    private ApplicationUser _user = default!;
    private bool _requirePassword;

    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = default!;

    protected override async Task OnInitializedAsync()
    {
        Input ??= new();

        _user = await UserAccessor.GetRequiredUserAsync();
        _requirePassword = await UserManager.HasPasswordAsync(_user);
    }

    private async Task OnValidSubmitAsync()
    {
        if (_requirePassword && !await UserManager.CheckPasswordAsync(_user, Input.Password!))
        {
            _message = "Error: Incorrect password.";
            return;
        }

        var result = await UserManager.DeleteAsync(_user);
        var userId = await UserManager.GetUserIdAsync(_user);
        if (!result.Succeeded)
        {
            throw new InvalidOperationException($"Unexpected error occurred deleting user.");
        }

        await SignInManager.SignOutAsync();

        Logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

        RedirectManager.RedirectToCurrentPage();
    }

    private sealed class InputModel
    {
        [DataType(DataType.Password)]
        public string? Password { get; set; }
    }
}
